package com.example.first.activities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.first.R;
import com.example.first.modle.AddressBook;
import com.example.first.modle.ApiResponse;
import com.example.first.modle.CartItem;
import com.example.first.modle.OrderSubmit;
import com.example.first.modle.OrderSubmitVO;
import com.example.first.services.ApiService;
import com.example.first.utils.RetrofitClient;

import java.math.BigDecimal;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderSubmitActivity extends AppCompatActivity {

   private ImageButton back;

   private TextView addressName;
   private TextView addressInfo;

   private TextView dishAmount;
   private TextView deliveryAmount;
   private TextView dabaoAmount;
   private TextView total_price;

   private EditText remark;

   private Button pay;

   private OrderSubmit orderSubmit;

   //存放地址信息
    private AddressBook addressBook;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_submit);

        // 设置 Toolbar 标题
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("外卖订餐");
        }


        // 设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#FFC300")); // 设置为你想要的颜色
        }


        //返回
        back = findViewById(R.id.back);
        back.setOnClickListener(v -> finish());

        addressName=findViewById(R.id.order_detail_address_name);
        addressInfo=findViewById(R.id.order_detail_address_info);

        orderSubmit=new OrderSubmit();
        //获取默认地址
        getdefaultAddress();

        pay=findViewById(R.id.pay);
        dishAmount=findViewById(R.id.dish_amount);
        deliveryAmount=findViewById(R.id.delivery_amount);
        dabaoAmount=findViewById(R.id.dabao_amount);
        total_price=findViewById(R.id.total_price);
        remark=findViewById(R.id.remark);

        //获取订单价值信息
        getAmount();

        pay.setOnClickListener(v -> {
            orderSubmit.setRemark(remark.getText().toString());
            if(orderSubmit.getAddressBookId()==null){
                return;
            }
            ApiService apiService= RetrofitClient.getApiService();
            Call<ApiResponse<OrderSubmitVO>> call=apiService.orderSubmit(orderSubmit);
            call.enqueue(new Callback<ApiResponse<OrderSubmitVO>>() {
                @Override
                public void onResponse(Call<ApiResponse<OrderSubmitVO>> call, Response<ApiResponse<OrderSubmitVO>> response) {
                    //TODO
                    if(response.isSuccessful()&& response.body()!=null){
                        ApiResponse<OrderSubmitVO> apiResponse=response.body();
                        if(apiResponse.getCode()==1){
                            Toast.makeText(OrderSubmitActivity.this, "下单成功", Toast.LENGTH_SHORT).show();
                            Intent intent=new Intent(OrderSubmitActivity.this,MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        }else {
                            Toast.makeText(OrderSubmitActivity.this, apiResponse.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                }

                @Override
                public void onFailure(Call<ApiResponse<OrderSubmitVO>> call, Throwable t) {

                }
            });

        });
    }

    //获取并设置默认地址信息
    public void getdefaultAddress(){
        ApiService apiService= RetrofitClient.getApiService();
        Call<ApiResponse<AddressBook>> call=apiService.getDefaultAddress();
        call.enqueue(new Callback<ApiResponse<AddressBook>>() {
            @Override
            public void onResponse(Call<ApiResponse<AddressBook>> call, Response<ApiResponse<AddressBook>> response) {
                if (response.isSuccessful()&& response.body()!=null){
                    if(response.body().getCode()==1){
                        addressBook=response.body().getData();
                        if(addressBook!=null){
                            orderSubmit.setAddressBookId(addressBook.getId());
                            addressInfo.setText(addressBook.getDetail());
                            addressName.setText(addressBook.getConsignee());
                        }else {
                            Toast.makeText(OrderSubmitActivity.this, "请先设置默认地址", Toast.LENGTH_SHORT).show();
                            finish();
                        }

                    }else {
                        Toast.makeText(OrderSubmitActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                    Toast.makeText(OrderSubmitActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<AddressBook>> call, Throwable t) {
                Toast.makeText(OrderSubmitActivity.this, "请求失败", Toast.LENGTH_SHORT).show();

            }
        });
    }

    //获取订单价值信息
    public void getAmount(){
        ApiService apiService= RetrofitClient.getApiService();
        Call<ApiResponse<List<CartItem>>> call=apiService.getCartList();
        call.enqueue(new Callback<ApiResponse<List<CartItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<CartItem>>> call, Response<ApiResponse<List<CartItem>>> response) {
                if (response.isSuccessful()&& response.body()!=null){
                    if(response.body().getCode()==1){
                        List<CartItem> list =response.body().getData();
                        if(list!=null&& !list.isEmpty()){
                            BigDecimal dishTotal=BigDecimal.ZERO;
                            for (CartItem cartItem : list) {
                                dishTotal=dishTotal.add(cartItem.getAmount().multiply(new BigDecimal(cartItem.getNumber())));
                            }
                            Integer deliveryTotal=6;
                            Integer dabaoTotal=list.size();
                            dishAmount.setText("￥"+dishTotal);
                            deliveryAmount.setText("￥"+deliveryTotal);
                            dabaoAmount.setText("￥"+dabaoTotal);
                            total_price.setText("￥"+(dishTotal.add(new BigDecimal(deliveryTotal)).add(new BigDecimal(dabaoTotal))));
                            orderSubmit.setPayMethod(2);
                            orderSubmit.setDeliveryStatus(1);
                            orderSubmit.setTablewareStatus(0);

                        }else {
                            Toast.makeText(OrderSubmitActivity.this, "请先添加菜品", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                    else {
                        Toast.makeText(OrderSubmitActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(OrderSubmitActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<CartItem>>> call, Throwable t) {
                Toast.makeText(OrderSubmitActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}